package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.entity.PageResult;
import com.itheima.mapper.MenuMapper;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service(interfaceClass = MenuService.class)
public class MenuServiceimpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    /**
     * 分页查询
     * @param currentPage
     * @param pageSize
     * @param queryString
     * @return
     */
    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        List<Menu> list = menuMapper.findPage(queryString);
        PageInfo<Menu> menuPageInfo = new PageInfo<>(list);

        return new PageResult(menuPageInfo.getTotal(), menuPageInfo.getList());
    }

    /**
     * 通过id检查组
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        Integer parentMenuId = null;
        try {
            parentMenuId = menuMapper.find(id);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }

        if (parentMenuId == null) {
            throw new RuntimeException("删除失败");
        }
        menuMapper.deleteById(id);
    }

    /**
     * 添加
     * @param menu
     */
    @Override
    public void add(Menu menu) {
        menuMapper.add(menu);
    }

    /**
     * 根据id查询
     * @param id
     */
    @Override
    public Menu findById(Integer id) {
        return menuMapper.findById(id);
    }

    /**
     * 编辑修改
     * @param menu
     */
    @Override
    public void edit(Menu menu) {
        menuMapper.edit(menu);
    }

    @Override
    public List<Menu> findMenuByUsername(String username) {
        List<Menu> menuList = menuMapper.findMenuByUsername(username);
        for (Menu menu : menuList) {
            String path = menu.getPath();
            List<Menu> childMenu = menuMapper.findMenuByUsername2(path);
            menu.setChildren(childMenu);
        }
        return menuList;
    }
}
